package com.easy.app.controller.system;

import com.easy.framework.common.enums.CommonStatus;
import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.StringUtil;
import com.easy.framework.common.validate.Add;
import com.easy.framework.common.validate.Update;
import com.easy.framework.web.base.BaseController;
import com.easy.module.log.annotation.Log;
import com.easy.module.log.enums.Operation;
import com.easy.module.system.entity.SysDept;
import com.easy.module.system.query.SysDeptQuery;
import com.easy.module.system.service.ISysDeptService;
import com.easy.module.system.service.ISysUserDeptService;
import com.easy.framework.common.model.TreeModel;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 *
 * @author Easy
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    private final ISysDeptService sysDeptService;

    private final ISysUserDeptService sysUserDeptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@perm.hasPermission('system:dept$list')")
    @GetMapping("/list")
    public R list(SysDeptQuery query)
    {
        return R.success(sysDeptService.queryList(query));
    }


    /**
     * 获取部门列表
     */
    @PreAuthorize("@perm.hasPermission('system:dept$list')")
    @GetMapping("/children")
    public R<List<SysDept>> children(SysDeptQuery query)
    {
        return R.success(sysDeptService.children(query));
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/tree")
    public R<List<TreeModel>> deptTree(SysDeptQuery query) {
        List<SysDept> deptList = sysDeptService.queryList(query);
        return R.success(sysDeptService.treeList(deptList));
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@perm.hasPermission('system:dept$list')")
    @GetMapping("/list/exclude/{deptId}")
    public R excludeChild(@PathVariable("deptId") Long deptId)
    {
        List<SysDept> depts = sysDeptService.queryList(new SysDeptQuery());
        depts.removeIf(d -> d.getId().intValue() == deptId || ArrayUtils.contains(StringUtil.split(d.getAncestors(), ","), deptId + ""));
        return R.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@perm.hasPermission('system:dept$query')")
    @GetMapping(value = "/{deptId}")
    public R get(@PathVariable("deptId") Long deptId)
    {
        sysDeptService.validateDataScope(deptId);
        return R.success(sysDeptService.getById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@perm.hasPermission('system:dept$add')")
    @Log(title = "部门管理", type = Operation.INSERT)
    @PostMapping
    public R add(@Validated({Add.class}) @RequestBody SysDept dept)
    {
        if (sysDeptService.exists(SysDept::getDeptName,dept.getDeptName()))
        {
            return R.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        return R.result(sysDeptService.add(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@perm.hasPermission('system:dept$edit')")
    @Log(title = "部门管理", type = Operation.UPDATE)
    @PutMapping
    public R edit(@Validated({Update.class}) @RequestBody SysDept dept)
    {
        Long deptId = dept.getId();
        sysDeptService.validateDataScope(deptId);
        if (sysDeptService.exists(SysDept::getDeptName,dept.getDeptName(),SysDept::getId,dept.getId()))
        {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (deptId.equals(dept.getParentId()))
        {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (CommonStatus.disabled.getValue().equals(dept.getStatus()) && sysDeptService.getEnabledChildDeptCountById(deptId) > 0)
        {
            return R.fail("该部门包含未停用的子部门！");
        }
        return R.result(sysDeptService.update(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@perm.hasPermission('system:dept$remove')")
    @Log(title = "部门管理", type = Operation.DELETE)
    @DeleteMapping("/{deptId}")
    public R remove(@PathVariable("deptId") Long deptId)
    {
        if (sysDeptService.hasChildByDeptId(deptId))
        {
            return R.fail("存在下级部门,不允许删除");
        }
        if (sysUserDeptService.hasUserByDeptId(deptId))
        {
            return R.fail("部门存在用户,不允许删除");
        }
        sysDeptService.validateDataScope(deptId);
        return R.result(sysDeptService.removeById(deptId));
    }
}
